package local.blueheart.springcloud.bhmicroserviceorder.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import local.blueheart.springcloud.bhmicroserviceorder.feign.ItemFeignClient;
import local.blueheart.springcloud.bhmicroserviceorder.pojo.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;


@Service
public class ItemService {

//    @Autowired
//    private RestTemplate restTemplate;

//    @Autowired
//    private DiscoveryClient discoveryClient;

    @Autowired
    private ItemFeignClient itemFeignClient;

    @HystrixCommand(fallbackMethod = "queryItemByIdFailCallback")
    public Item queryItemById(Long id) {
        return this.itemFeignClient.queryItemById(id);
    }

//    @HystrixCommand(fallbackMethod = "queryItemByIdFailCallback")
//    public Item queryItemById(Long id) {
//
//        String serviceId = "bh-microservice-item";
//        return this.restTemplate.getForObject("http://" + serviceId + "/item/" + id, Item.class);
//    }

    public Item queryItemByIdFailCallback(Long id) {
        return new Item(1L,"商品信息失败",null,null,1L);
    }

//    public Item queryItemById(Long id) {
//
//        String serviceId = "bh-microservice-item";
//        List<ServiceInstance> instances = this.discoveryClient.getInstances(serviceId);
//        if(instances.isEmpty()){
//            return null;
//        }
//        ServiceInstance serviceInstance = instances.get(0);
//        String url = serviceInstance.getHost()+":"+serviceInstance.getPort();
//        return this.restTemplate.getForObject("http://"+url+"/item/"+id,Item.class);
//    }
}
